<!DOCTYPE html>
<html>

<head>
  <style>
    #txt_api_contentType,
    #txt_api_author,
    .txt_id {
      font-size: 0.8rem;
      font-weight: normal;
    }

    .api_changer {
      font-size: 0.8rem;
      font-weight: normal;
      padding-left: 10px;
    }

    .table_api_params,
    .table_api_envs {
      border-collapse: collapse;
      border-spacing: 0;
    }

    .table_api_params td,
    .table_api_envs td,
    .table_api_envs th,
    .table_api_params th {
      border-left: 1px solid #88888855;
      padding: 4px 6px;
    }

    .table_api_params td:first-child,
    .table_api_envs td:first-child,
    .table_api_envs th:first-child,
    .table_api_params th:first-child {
      border-left: none;
      padding: 4px 6px;
    }

    html,
    body {
      padding: 0px;
      max-height: 100%;
      zoom: 1.05;
    }

    body {
      position: absolute;
      inset: 0px;
      overflow: hidden;
      padding: 0px;
      margin: 0px;
      display: flex;
      flex-direction: column;
    }

    .header {
      padding: 10px;
      border-bottom: 1px solid #88888855;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
    }

    .header h2 {
      margin: 0px;
    }

    .content {
      padding: 10px;
      overflow: auto;
    }

    .content h4 {
      margin: 16px 0px;
    }

    .table_row_0 {
      background: #88888811
    }

    .table_row_1 {
      background: transparent;
    }

    #txt_api_creatorName,
    #txt_api_modifierName,
    #txt_api_id,
    #txt_api_moduleId,
    #txt_api_projectId {
      font-weight: bold;
    }

    .icon_btn {
      user-select: none;
      cursor: pointer;
      border-radius: 5px;
      transition: transform 200ms;
      display: inline-block;
      font-size: 16px;
      padding: 5px 5px;
    }

    .icon_btn:hover {
      transform: scale(1.2);
      transform-origin: 50% 50%;
    }

    .icon_btn:active {
      transform: scale(1)
    }
  </style>
</head>

<body>
  <div class="header">
    <h2>
      <span id="txt_api_name"></span>
      <div class="api_changer">
        <span class="txt_id">
          project：<span id="txt_api_projectId"></span>&nbsp;
          module：<span id="txt_api_moduleId"></span>&nbsp;
          ID：<span id="txt_api_id"></span>
        </span>
      </div>
      <div class="api_changer">
        created:<span id="txt_api_creatorName"></span>
        at <span id="txt_api_gmtCreate"></span>
      </div>
      <div class="api_changer">
        last modified by <span id="txt_api_modifierName"></span>
        at <span id="txt_api_gmtModified"></span>
      </div>
    </h2>
    <div>
      <div class="icon_btn" id="btn_gen">
        ⏏️
      </div>
      <div class="icon_btn" id="btn_refresh">
        🔄️
      </div>
    </div>
  </div>
  <div class="content">
    <h4>
      Author
      <span id="txt_api_author"></span>
    </h4>
    <h4>URL</h4>
    <table class="table_api_envs">
      <tbody id="tbody_api_envs"></tbody>
    </table>
    <h4>Description</h4>
    <div id="txt_api_description"></div>
    <h4>
      ContentType
      <span id="txt_api_contentType"></span>
    </h4>
    <div id="div_request_path_params_zone">
      <h4>Path Parameter</h4>
      <table class="table_api_params">
        <thead>
          <tr>
            <th> name </th>
            <th> type </th>
            <th> description </th>
            <th> example </th>
          </tr>
        </thead>
        <tbody id="tbody_api_path_params"></tbody>
      </table>
    </div>
    <div id="div_request_query_zone">
      <h4>Query Parameter</h4>
      <table class="table_api_params">
        <thead>
          <tr>
            <th> name </th>
            <th> type </th>
            <th> description </th>
            <th> example </th>
          </tr>
        </thead>
        <tbody id="tbody_api_query"></tbody>
      </table>
    </div>
    <div id="div_request_body_zone">
      <h4>Request Parameter</h4>
      <table class="table_api_params">
        <thead>
          <tr>
            <th> name </th>
            <th> type </th>
            <th> description </th>
            <th> example </th>
          </tr>
        </thead>
        <tbody id="tbody_api_body"></tbody>
      </table>
    </div>
    <div id="div_request_resp_zone">
      <h4>Response</h4>
      <table class="table_api_params">
        <thead>
          <tr>
            <th> name </th>
            <th> type </th>
            <th> description </th>
            <th> example </th>
          </tr>
        </thead>
        <tbody id="tbody_api_response"></tbody>
      </table>
    </div>
  </div>
  <script>
    (function () {
      function getEle(eleId) {
        return document.getElementById(eleId)
      }
      function setTxt(eleId, text) {
        getEle(eleId).innerHTML = text
      }
      /** @type {{<K extends keyof HTMLElementDeprecatedTagNameMap>(tag:K,parent?:HTMLElement)=> HTMLElementDeprecatedTagNameMap[K]}} */
      const newEle = function (tag, parent) {
        const ret = document.createElement(tag);
        parent && parent.append(ret);
        return ret;
      }
      const data = $_DOC_DATA
      const { detail } = data;

      const vscode = window.acquireVsCodeApi && acquireVsCodeApi();
      vscode?.setState(data)

      setTxt('txt_api_name', '[' + (detail.httpMethod || 'Unknown') + '] ' + detail.name);
      setTxt('txt_api_author', detail.author);
      setTxt('txt_api_id', detail.id);
      setTxt('txt_api_creatorName', detail.creatorName);
      setTxt('txt_api_modifierName', detail.modifierName);
      setTxt('txt_api_gmtCreate', detail.gmtCreate);
      setTxt('txt_api_gmtModified', detail.gmtModified);
      setTxt('txt_api_description', detail.description);
      setTxt('txt_api_contentType', detail.contentType);
      setTxt('txt_api_projectId', detail.projectId);
      setTxt('txt_api_moduleId', detail.moduleId);

      detail.debugEnvs.map(function (info, idx) {
        const tr = newEle('tr');
        tr.className = 'table_row_' + (idx % 2)
        const td0 = newEle('td', tr).innerHTML = info.name;
        const td1 = newEle('td', tr).innerHTML = info.url + detail.url;
        getEle('tbody_api_envs').append(tr);
      });

      function renderParams(tbodyId, params) {
        /**
         * @type {{[key in string]?: typeof detail.responseParams[0]}}
         */
        const paramsMap = {};
        const getParentChain = function (id) {
          const ret = []
          let parentId = id;
          while (parentId) {
            (parentId !== id) && ret.push(parentId);
            parentId = paramsMap[parentId]?.parentId;
          }
          return ret;
        }

        params.forEach(param => paramsMap[param.id] = param)
        /**
         * @type {typeof detail.responseParams}
         */
        const sortedParams = [];
        const collapsibles = {};
        const collapseed = {};

        const update = () => {
          const children = getEle(tbodyId).children;
          for (let i = 0; i < children.length; ++i) {
            const child = children[i];
            child.style.display = getParentChain(child.id).some(id => collapseed[id]) ? 'none' : ''
          }
        }

        const handling = [''];
        while (handling.length) {
          const parentId = handling[0];
          const idx = Math.max(0, sortedParams.findIndex(v => v.id === parentId))
          const children = params.filter(v => v.parentId === parentId)
          collapsibles[parentId] = !!children.length
          sortedParams.splice(idx + 1, 0, ...children)
          handling.splice(0, 1);
          handling.push(...children.map(v => v.id));
        }

        sortedParams.map(function (param, idx, length) {
          const tr = newEle('tr');
          tr.id = param.id;
          tr.className = 'table_row_' + (idx % 2)
          param.parentId && tr.setAttribute('parent_id', param.parentId);

          const td_name = newEle('td', tr);
          const spaceCount = getParentChain(param.id).length

          for (let i = 0; i < spaceCount; ++i) {
            td_name.append('    ')
          }

          /**
           * @type {HTMLButtonElement}
           */
          const cb = newEle('span');
          cb.setAttribute('checked', 'false')
          cb.innerHTML = '▸';
          cb.style.userSelect = 'none';
          if (collapsibles[param.id]) {
            cb.style.cursor = 'pointer';
            cb.addEventListener('click', function (e) {
              const checked = cb.getAttribute('checked') !== 'true'
              cb.setAttribute('checked', checked)
              collapseed[param.id] = checked;
              cb.innerHTML = checked ? '▸' : '▾';
              update();
            })
          } else {
            cb.style.opacity = '0'
          }
          td_name.append(cb);
          td_name.append(param.name);
          td_name.style.whiteSpace = 'pre'
          td_name.style.wordBreak = 'keep-all'

          newEle('td', tr).append(param.type);
          newEle('td', tr).append(param.description);

          const td_example = newEle('td', tr);
          td_example.append(param.example);
          td_example.style.whiteSpace = 'pre'
          td_example.style.wordBreak = 'keep-all'

          getEle(tbodyId).append(tr);
        });
      }

      if (detail.queryParams.length)
        renderParams('tbody_api_query', detail.queryParams);
      else
        getEle('div_request_query_zone').remove()

      if (detail.requestParams.length)
        renderParams('tbody_api_body', detail.requestParams);
      else
        getEle('div_request_body_zone').remove()

      if (detail.responseParams.length)
        renderParams('tbody_api_response', detail.responseParams);
      else
        getEle('div_request_resp_zone').remove()

      if (detail.pathParams.length)
        renderParams('tbody_api_path_params', detail.pathParams);
      else
        getEle('div_request_path_params_zone').remove()


      getEle('btn_gen').onclick = () => vscode?.postMessage({ type: 'gen' })
      getEle('btn_refresh').onclick = () => vscode?.postMessage({ type: 'refresh' })

    })()

  </script>
</body>

</html>